
#include <algorithm>
#include <string>
#include "functions.h"
#include "config.h"

//*************************************************************************
// File Name: functions.cpp
// This is the implementation file for various functions used to check
// for failed openings of files and converts and return time formats
// "Group 3"
// CS 1C
// March 25, 2010
// Group Project: SuperWarehouse
// Due: March 25, 2010
// - KZ's comment
//*************************************************************************

void debugMsg(const char *msg) {
	debugMsg(string(msg));
}

void debugMsg(string msg) {
	cout << "DEBUG: " << msg << endl;
}

void errorMsg(const char *msg) {
	errorMsg(string(msg));
}

void errorMsg(string msg) {
	cout << "ERROR: " << msg << endl;
}

void statusMsg(const char *msg) {
	statusMsg(string(msg));
}

void statusMsg(string msg) {
	cout << "STATUS: " << msg << endl;
}


time_t timestampFromDateString(string theDate) {
	int month, day, year;
	time_t rawtime;
	struct tm *timeinfo;
	const char *buf;

	time(&rawtime);
	timeinfo = localtime(&rawtime);

	buf = theDate.c_str();

	sscanf(buf, "%d/%d/%d", &month, &day, &year);

	timeinfo->tm_year = year > 1900 ? year - 1900 :
			year > 80 ? year : year + 100;
	timeinfo->tm_mon = month - 1;
	timeinfo->tm_mday = day;

	return mktime(timeinfo);
}

string dateStringFromTimestamp(time_t timestamp) {
	struct tm *timeinfo;
	char buf[200];
	int month, day, year;

	timeinfo = localtime(&timestamp);

	month = timeinfo->tm_mon + 1;
	day = timeinfo->tm_mday;
	year = timeinfo->tm_year + 1900;

	sprintf(buf, "%04d-%02d-%02d", year, month, day);

	return string(buf);
}

string salesReportFilenameForDay(time_t day) {
	string dateString;
	string path;
	char buf[200];

	dateString = dateStringFromTimestamp(day);

	sprintf(buf, "%s/sales_%s.txt", REPORTS_DIR, dateString.c_str());

	return string(buf);
}

time_t currentTime() {
	if (OVERRIDE_CURRENT_TIME > 0) {
		return OVERRIDE_CURRENT_TIME;
	} else {
		return time(NULL);
	}
}

time_t nextMonth(time_t timestamp) {
	// TODO: Improve accuracy
	return timestamp + (3600 * 24 * 31);
}

void chomp(string &str) {
	if (!str.empty() && str[str.length() - 1] == '\n') {
		str.erase(str.length() - 1);
	}
	if (!str.empty() && str[str.length() - 1] == '\r') {
		str.erase(str.length() - 1);
	}
}

void chomp(char *str) {
	int i, n;
	n = strlen(str);
	for (i = 0; i < n; i++) {
		if (str[i] == '\r' || str[i] == '\n') {
			str[i] = 0;
			break;
		}
	}
}

